﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace leastSquareMethod
{/// <summary>
/// 最小二乘法模型
/// x轴是年，y轴是GDP总值
/// </summary>
    internal class LeastSquareMethod
    {
       public static double leastsquaremethod(Points[] objs, int year)
        {
            double sumX = 0;
            double sumY = 0;
            foreach (Points obj in objs)
            {
                sumX += obj.X;
                sumY += obj.Y;
            }
            double averX = 0;//年的总数的平均
            double averY = 0;//GDP总数的平均
            double slope = 0;//斜率
            double intercept = 0;//截距

            averX = sumX / objs.Length;
            averY = sumY / objs.Length;
            double Molecular = 0;
            double Denominator = 0;
            foreach (Points obj in objs)
            {
                Molecular += (obj.X - averX) * (obj.Y - averY);//分子
                Denominator += Math.Pow((obj.X - averX), 2);//分母
            }
            slope = Molecular / Denominator;
            intercept = averY - slope * averX;
            return intercept + slope * year;//返回预测值
        }
    }
}
